package com.dragon.modules.yuegou.service.impl.busd;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.yuegou.entity.busd.DistrictEntity;
import com.dragon.modules.yuegou.entity.busd.GroupEntity;
import com.dragon.modules.yuegou.entity.system.AddressEntity;
import com.dragon.modules.yuegou.entity.system.DataAccessEntity;
import com.dragon.modules.yuegou.enums.busd.DistrictStatus;
import com.dragon.modules.yuegou.enums.busd.GroupStatus;
import com.dragon.modules.yuegou.enums.code.BusinessCode;
import com.dragon.modules.yuegou.enums.system.DataAccessOwnerType;
import com.dragon.modules.yuegou.mapper.busd.GroupMapper;
import com.dragon.modules.yuegou.model.busd.District;
import com.dragon.modules.yuegou.model.busd.Group;
import com.dragon.modules.yuegou.properties.PostersProperties;
import com.dragon.modules.yuegou.query.busd.DistrictQuery;
import com.dragon.modules.yuegou.query.busd.GroupBusQuery;
import com.dragon.modules.yuegou.query.busd.GroupQuery;
import com.dragon.modules.yuegou.query.system.DataAccessQuery;
import com.dragon.modules.yuegou.service.busd.DistrictService;
import com.dragon.modules.yuegou.service.busd.GroupService;
import com.dragon.modules.yuegou.service.system.AddressService;
import com.dragon.modules.yuegou.service.system.DataAccessService;
import com.dragon.modules.yuegou.web.Check;
import com.dragon.modules.yuegou.web.DataSliceUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 集团表 服务实现
 *
 * @author pbuilder generated
 * @date 2019-03-19 08:59:40
 * @version 2.0
 */
@Service("busdGroupService")
public class GroupServiceImpl
		extends ServiceImpl<GroupMapper, GroupEntity>
		implements GroupService {

	@Autowired
	private DistrictService districtService;
	
	@Autowired
	private AddressService addressService;
	
	@Autowired
	private DataAccessService dataAccessService;

	@Autowired
	private PostersProperties postersProperties;

	@Override
	public List<Group> groupDistrict(String userId) {
		GroupQuery groupQuery = new GroupQuery();
		groupQuery.setDel(false);
		List<GroupEntity> entities= baseMapper.selectList(groupQuery.toQueryWrapper());
		List<Group> groupList = entities.stream().map(Group::new).collect(Collectors.toList());

		for (Group group : groupList) {
			DistrictQuery districtQuery = new DistrictQuery();
			districtQuery.setGroupId(group.getId());
			groupQuery.setDel(false);
			List<DistrictEntity> districtEntities = districtService.list(districtQuery.toQueryWrapper());
			List<District> districtList = districtEntities.stream().map(District::new).collect(Collectors.toList());
			for (District district : districtList) {
				district.setSelected(false);
				DataAccessQuery dataAccessQuery = new DataAccessQuery();
				dataAccessQuery.setUserId(userId);
				dataAccessQuery.setGroupId(group.getId());
				dataAccessQuery.setBusdId(district.getId());
				dataAccessQuery.setOwnerType(DataAccessOwnerType.PLATFORM);
				List<DataAccessEntity> list = dataAccessService.list(dataAccessQuery.toQueryWrapper());
				if (list.size() > 0) {
					district.setSelected(true);
				}
			}
			group.setDistrictList(districtList);
		}
		return groupList;
	}

	@Override
	public Group groupDistrictByGroup(String userId,String groupId) {
		Check.notEmpty(userId, "userId is required");
		Check.notEmpty(groupId, "groupId is required");
		GroupQuery groupQuery = new GroupQuery();
		groupQuery.setDel(false);
		GroupEntity groupEntity = baseMapper.selectById(groupId);
		Group group = new Group(groupEntity);
		setDistrict(group,null);
		return group;
	}

	@Override
	public List<District> listMyDistrict(String userId) {
		// 商圈节点在第三层
		List<District> list = new ArrayList<>();

		// 提供前段切换的数据切片不止是商圈，还有大运营平台
		District platform = new District();
		platform.setId(DataSliceUtils.PLATFORM_DATA_ID);
		platform.setBcName("大运营平台");
		list.add(0, platform);
		
		return list;
	}

	
	@Override
	public IPage<Group> search(PageRequest page, GroupBusQuery query) {
		IPage<GroupEntity> pa = new Page<>(page.getPage(), page.getSize(), true);

		//查询分页的集团信息
		IPage<Group> iPage = baseMapper.pageSearch(pa, query);
		for (Group group : iPage.getRecords()) {
			setDistrict(group,query.getBcName());
		}
		return iPage;
	}

	private void setDistrict(Group group,String bcName){
		//获取集团市区地址信息
		String areaCode = group.getAreaCode();
		if (!StringUtils.isEmpty(areaCode)) {
			AddressEntity addressQ = addressService.getById(areaCode);
			AddressEntity addressS = addressService.getById(areaCode.substring(0, areaCode.length()-4)+"0000");
			group.setArea(addressQ.getName());
			group.setCity(addressS.getName());
		}
		//查询集团下的商圈信息
		DistrictQuery districtQuery = new DistrictQuery();
		districtQuery.setDel(false);
		districtQuery.setGroupId(group.getId());
		districtQuery.bcName().like(bcName);
		List<DistrictEntity> districtEntities = districtService.list(districtQuery.toQueryWrapper());
		List<District> districtList = districtEntities.stream().map(District::new).collect(Collectors.toList());
		for (District district : districtList) {
			//获取商圈市区地址信息
			String districtCode = district.getAreaCode();
			if (!StringUtils.isEmpty(districtCode)) {
				AddressEntity districtQ = addressService.getById(districtCode);
				AddressEntity districtS = addressService.getById(districtCode.substring(0, districtCode.length()-4)+"0000");
				district.setArea(districtQ.getName());
				district.setCity(districtS.getName());
			}
		}
		group.setDistrictList(districtList);
	}

	@Override
	public IPage<Group> searchGroup(PageRequest page, GroupBusQuery query) {
		IPage<GroupEntity> pa = new Page<>(page.getPage(), page.getSize(), true);

		//查询分页的集团信息
		GroupQuery groupQuery = new GroupQuery();
		groupQuery.setDel(false);
		groupQuery.setStatus(GroupStatus.ENABLED);
		IPage<GroupEntity> iPage = baseMapper.selectPage(pa, groupQuery.toQueryWrapper());
		IPage<Group> iPageGroup = iPage.convert(Group::new);
		for (Group group : iPageGroup.getRecords()) {
			setDistrict(group,query.getBcName());
		}
		return iPageGroup;
	}

	@Override
	public void saveGroup(Group group) {
		Check.notNull(group.getGroupName(),"集团姓名不能为空");
		Check.length(group.getGroupName(), 0, 20, "集团姓名长度大于20位");
		if (!StringUtils.isEmpty(group.getContactPhone()) && com.dragon.modules.yuegou.utils.PrivateStringUtils.isNotMobileNO(group.getContactPhone())) {
			throw new DragonException(BusinessCode.PHONE_WRONG_FORMAT);
		}
		//判断集团名是否存在
		GroupQuery groupQuery = new GroupQuery();
		groupQuery.setGroupName(group.getGroupName());
		groupQuery.setDel(false);
		List<GroupEntity> list = baseMapper.selectList(groupQuery.toQueryWrapper());
		if (StringUtils.isEmpty(group.getId())) {
			if (list.size()>0) {
				throw new DragonException(BusinessCode.GROUP_NAME_EXISTS);
			}
			group.setBusdQuantity(0);
			group.setUserQuantity(0);
			//插入集团信息
			group.setStatus(GroupStatus.ENABLED);
			save(group);
		}else {
			if (list.size()>0 && !list.get(0).getId().equals(group.getId())) {
				throw new DragonException(BusinessCode.GROUP_NAME_EXISTS);
			}
			baseMapper.updateById(group);
		}
	}

	@Override
	public Group groupById(String groupId) {
		Check.notNull(groupId, "groupId不能为空");
		GroupEntity entity = baseMapper.selectById(groupId);
		Group group = new Group(entity);
		if(!StringUtils.isEmpty(group.getAreaCode())) {
			AddressEntity districtQ = addressService.getById(group.getAreaCode());
			AddressEntity districtS = addressService.getById(group.getAreaCode().substring(0, group.getAreaCode().length() - 4) + "0000");
			AddressEntity districtP = addressService.getById(group.getAreaCode().substring(0, group.getAreaCode().length() - 8) + "00000000");
			group.setProvince(districtP.getName());
			group.setArea(districtQ.getName());
			group.setCity(districtS.getName());
			group.setProvinceId(districtP.getId());
			group.setAreaId(districtQ.getId());
			group.setCityId(districtS.getId());
		}
		return group;
	}

	@Override
	public void groupLicense(Group group) {
		baseMapper.updateById(group);
	}

	@Override
	public void personalise(Group group) {
		//判断集团名称是否重复
		GroupQuery groupQuery = new GroupQuery();
		groupQuery.setGroupName(group.getGroupName());
		groupQuery.setDel(false);
		List<GroupEntity> groupList = baseMapper.selectList(groupQuery.toQueryWrapper());
		if (groupList.size() > 0 && !groupList.get(0).getId().equals(group.getId())) {
			throw new DragonException(BusinessCode.GROUP_NAME_EXISTS);
		}
		baseMapper.updateById(group);
	}

	@Transactional
	@Override
	public void endisableGroup(String groupId, GroupStatus groupStatus) {
		DistrictStatus districtStatus = DistrictStatus.from(groupStatus.getCode());
		//查询集团下所有商圈信息
		DistrictQuery districtQuery = new DistrictQuery();
		districtQuery.setGroupId(groupId);
		List<DistrictEntity> districtList = districtService.list(districtQuery.toQueryWrapper());
		//循环修改所有商圈在状态
		for (DistrictEntity district : districtList) {
			district.setStatus(districtStatus);
			districtService.updateById(district);
		}
		//修改集团的状态
		GroupEntity group = getById(groupId);
		group.setStatus(groupStatus);
		baseMapper.updateById(group);
	}
	@Override
	public String getMiniAppIdByBusdId(String busdId) {
		if(!StringUtils.isEmpty(busdId)){
			District district = districtService.getDistrictById(busdId);
			if (null != district.getGroupId()) {
				GroupEntity group = baseMapper.selectById(district.getGroupId());
				if (null != group.getMiniAppid()) {
					return group.getMiniAppid();
				}
			}
		}

		return postersProperties.getAppId();
	}

	@Override
	public String getAppIdByBusdId(String busdId) {
		if(!StringUtils.isEmpty(busdId)){
			District district = districtService.getDistrictById(busdId);
			if (null != district.getGroupId()) {
				GroupEntity group = baseMapper.selectById(district.getGroupId());
				if (null != group.getAppId()) {
					return group.getAppId();
				}
			}
		}
		return "";
	}
}